#include "StdAfx.h"
#include "LayoutView.h"

LayoutView::LayoutView(QWidget* owner):previousMousePosition_(-10000,-10000), QGraphicsView(owner)
{
	
	setScene(&scene_);
		
	//scene_.setBackgroundBrush(QBrush(Qt::lightGray, Qt::CrossPattern));
	drawGrid(QRect(x() * 100, y() * 100, width() * 100, height() * 100));

	scale(1,1);
	//setBackgroundBrush(Qt::blue);
}


LayoutView::~LayoutView(void)
{
}

QList<QGraphicsItem*> LayoutView::getSelectedItem()
{
	return scene_.selectedItems();
}

void LayoutView::drawGrid(const QRect rect)
{
	int gridInterval = 50; //interval to draw grid lines at
    
    qreal left = int(rect.left()) - (int(rect.left()) % gridInterval);
    qreal top = int(rect.top()) - (int(rect.top()) % gridInterval);

	int temp = rect.bottom();
    
    QVarLengthArray<QLineF, 100> linesX;
    for (qreal x = left; x < rect.right(); x += gridInterval)
	{
		scene_.addLine(x, rect.top(), x, rect.bottom());
	}
     
    QVarLengthArray<QLineF, 100> linesY;
    for (qreal y = top; y < rect.bottom(); y += gridInterval)
	{
		scene_.addLine(rect.left(), y, rect.right(), y);
	}
}
void LayoutView::mousePressEvent(QMouseEvent * event)
{
	QGraphicsView::mousePressEvent(event);
	
	auto scenePos = mapToScene(event->pos());
	previousMousePosition_ = scenePos;
}
void LayoutView::mouseReleaseEvent(QMouseEvent * event)
{
	QGraphicsView::mouseReleaseEvent(event);

}
void LayoutView::OnSelectionChanged(ObjectVisual* caller) 
{
	emit SelectionChanged();
}
void LayoutView::mouseMoveEvent(QMouseEvent * event)
{

	if(event->modifiers() == Qt::ShiftModifier)
	{

		auto scenePos = mapToScene(event->pos());
		for(auto it = visualsMap_.begin(); it != visualsMap_.end(); it++)
		{
			auto objVisual = it.value();
			if(objVisual->isSelected())
			{
				//possible memory leak
				//TODO:

				auto prevPositionInItemSpace = objVisual->mapFromScene(previousMousePosition_);
				auto curPositionInItemSpace = objVisual->mapFromScene(scenePos);
				objVisual->handleMouseDrag(prevPositionInItemSpace, curPositionInItemSpace);
			}
		}
		previousMousePosition_ = scenePos;
	}
	else
	{		
		QGraphicsView::mouseMoveEvent(event);
	}
}